<template>
  <div class="login">
    <div class="login_box">
      <div class="logo">
        <img src="https://img01.shenshisports.com/default/shenshi-logoV3.png" alt="" />
      </div>
      <h3 class="title">{{ title }}</h3>
      <template v-if="!isRegister">
        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
          <div v-if="!loginNext">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                type="text"
                auto-complete="off"
                placeholder="账号"
              >
                <template v-slot:prefix>
                  <img
                    src="@/assets/images/icon/mobile_icon.png"
                    style="width: 17px; height: 25x"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                auto-complete="off"
                placeholder="密码"
                @keyup.enter="handleLogin"
              >
                <template v-slot:prefix>
                  <img src="@/assets/images/icon/pwd_icon.png" style="width: 20px; height: 25px" />
                </template>
              </el-input>
            </el-form-item>
            <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px"
              >记住密码</el-checkbox
            >
            <el-form-item style="width: 100%">
              <el-button
                :loading="loginNextLogin"
                size="small"
                type="primary"
                style="width: 100%"
                @click.prevent="handleNext"
                class="login_btn"
              >
                <span v-if="!loginNextLogin">下一步</span>
                <span v-else>登录中...</span>
              </el-button>
              <div style="float: right" v-if="register">
                <router-link class="link-type" :to="'/register'">立即注册</router-link>
              </div>
              <div class="form_btm">
                <p class="register" @click="handleType(0)">立即注册</p>
              </div>
            </el-form-item>
          </div>

          <div v-if="loginNext">
            <el-form-item key="mobile">
              <el-input v-model="loginForm.mobile" placeholder="请输入手机号" :readonly="true">
                <template v-slot:prefix>
                  <img
                    src="@/assets/images/icon/mobile_icon.png"
                    style="width: 20px; height: 25px"
                  />
                </template>
                <template v-slot:suffix>
                  <el-button
                    type="text"
                    :disabled="countdown > 0"
                    @click="getSmsCode"
                    class="code_btn"
                  >
                    {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="mobileCode" key="mobileCode">
              <el-input v-model="loginForm.mobileCode" placeholder="请输入手机验证码">
                <template v-slot:prefix>
                  <img src="@/assets/images/icon/pwd_icon.png" style="width: 20px; height: 25px" />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="code" v-if="captchaEnabled">
              <div class="code_box">
                <el-input
                  v-model="loginForm.code"
                  auto-complete="off"
                  placeholder="验证码"
                  style="width: 63%"
                  @keyup.enter="handleLogin"
                >
                  <template v-slot:prefix>
                    <img
                      src="@/assets/images/icon/code_icon.png"
                      style="width: 22px; height: 25x"
                    />
                  </template>
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
              </div>
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button
                :loading="loginNextLogin"
                size="small"
                type="primary"
                style="width: 100%"
                @click.prevent="handleNext"
                class="login_btn"
              >
                <span v-if="!loginNextLogin">上一步</span>
                <span v-else>登录中...</span>
              </el-button>
              <div style="float: right" v-if="register">
                <router-link class="link-type" :to="'/register'">立即注册</router-link>
              </div>
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button
                :loading="loading"
                size="small"
                type="primary"
                style="width: 100%"
                @click.prevent="handleLogin"
                class="login_btn"
              >
                <span v-if="!loading">登录</span>
                <span v-else>登录中...</span>
              </el-button>
              <div style="float: right" v-if="register">
                <router-link class="link-type" :to="'/register'">立即注册</router-link>
              </div>
              <div class="form_btm">
                <p class="register" @click="handleType(0)">立即注册</p>
              </div>
            </el-form-item>
          </div>
        </el-form>
      </template>
      <template v-else>
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
        >
          <div class="go_login">
            已有账号，前去
            <span @click="handleType(1)">登录</span>
          </div>
          <template v-if="stepIndex == 0">
            <el-form-item prop="deptName" key="deptName">
              <el-input
                v-model="registerForm.deptName"
                type="text"
                auto-complete="off"
                placeholder="请输入公司名"
              >
                <template v-slot:prefix>
                  <img
                    src="@/assets/images/icon/stadium_icon.png"
                    style="width: 25px; height: 25x"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="phone" key="phone">
              <el-input
                v-model="registerForm.phone"
                type="text"
                auto-complete="off"
                placeholder="请输入手机号"
              >
                <template v-slot:prefix>
                  <img
                    src="@/assets/images/icon/mobile_icon.png"
                    style="width: 17px; height: 25x"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="code" key="code">
              <el-input v-model="registerForm.code" placeholder="请输入验证码">
                <template v-slot:prefix>
                  <img src="@/assets/images/icon/pwd_icon.png" style="width: 20px; height: 25px" />
                </template>
                <template v-slot:suffix>
                  <el-button
                    type="text"
                    :disabled="countdown > 0"
                    @click="getSmsCode"
                    class="code_btn"
                  >
                    {{ countdown > 0 ? `${countdown}秒` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button type="primary" style="width: 100%" @click.prevent="handleStep(1)">
                下一步
              </el-button>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item prop="userName" key="userName">
              <el-input
                v-model="registerForm.userName"
                type="text"
                auto-complete="off"
                placeholder="输入用户名"
              >
                <template v-slot:prefix>
                  <img
                    src="@/assets/images/icon/mobile_icon.png"
                    style="width: 17px; height: 25x"
                  />
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password" key="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                auto-complete="off"
                placeholder="输入密码（6-20个字符）"
                maxlength="20"
                show-password
              >
                <template v-slot:prefix>
                  <img src="@/assets/images/icon/pwd_icon.png" style="width: 17px; height: 25x" />
                </template>
              </el-input>
            </el-form-item>
            <div class="form_btn">
              <div class="step_btn" @click="handleStep(0)">上一步</div>
              <div class="register_btn" @click="handleRegister">立即注册</div>
            </div>
          </template>
        </el-form>
      </template>
    </div>

    <!--  底部  -->
    <div class="el-login-footer">
      <a style="font-size: 1.5vh; color: black" href="https://beian.miit.gov.cn/"
        >ICP备案/许可证号:沪ICP备2025124030号-3</a
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, useTemplateRef } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { debounce } from 'lodash'
import {
  getCodeImg,
  sendLoginNoByPhone,
  checkPhone,
  registerPcUser,
  sendLoginNoByName,
  getMobile,
} from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'

defineOptions({
  name: 'Login',
})

const router = useRouter()
const route = useRoute()
const store = useStore()

const title = import.meta.env.VITE_APP_TITLE
const codeUrl = ref('')
const loading = ref(false)
const captchaEnabled = ref(true)
const register = ref(false)
const isRegister = ref(false)
const phoneRegex = /^1[3-9]\d{9}$/
const countdown = ref(0)
const stepIndex = ref(0)
const loginNext = ref(false)
const loginNextLogin = ref(false)
const timer = ref<any>(null)
const redirect = ref<string | undefined>(undefined)

// 表单引用
const loginFormRef = useTemplateRef('loginFormRef')
const registerFormRef = useTemplateRef('registerFormRef')

// 登录表单数据
const loginForm = reactive<Record<string, any>>({
  username: '',
  password: '',
  rememberMe: false,
  mobileCode: '',
  code: '',
  uuid: '',
  mobile: '',
})

// 注册表单数据
const registerForm = reactive({
  deptName: '',
  phone: '',
  code: '',
  phonenumber: '',
  userName: '',
  password: '',
})

// 登录表单验证规则
const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  mobileCode: [{ required: true, trigger: 'change', message: '请输入手机验证码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
}

// 校验手机号
const validatePhone: Fn = (rule: any, value: string, callback: Fn) => {
  if (!value) {
    callback(new Error('请输入手机号'))
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入有效的手机号'))
  } else {
    callback()
  }
}
// 注册表单验证规则
const registerRules = {
  deptName: [
    {
      required: true,
      message: '请输入公司名',
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'blur',
    },
    {
      validator: validatePhone,
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
  ],
  userName: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      pattern: /^.{6,20}$/,
      message: '密码长度必须为6-20位字符',
      trigger: 'blur',
    },
  ],
}

// 路由监听
watch(
  () => route,
  (newRoute) => {
    redirect.value = newRoute.query?.redirect as string
  },
  { immediate: true },
)

// 组件挂载时获取验证码和cookie
onMounted(() => {
  getCode()
  getCookie()
})

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

// 获取登录验证码
const getCode = () => {
  getCodeImg().then((res) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.uuid = res.uuid
    }
  })
}

// 获取cookie
const getCookie = () => {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  loginForm.username = username === undefined ? loginForm.username : username
  loginForm.password = password === undefined ? loginForm.password : decrypt(password)
  loginForm.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)
}

// 处理登录
const handleLogin = () => {
  loginFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      if (loginForm.rememberMe) {
        Cookies.set('username', loginForm.username, { expires: 30 })
        Cookies.set('password', encrypt(loginForm.password), {
          expires: 30,
        })
        Cookies.set('rememberMe', loginForm.rememberMe.toString(), {
          expires: 30,
        })
      } else {
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('rememberMe')
      }
      store
        .dispatch('Login', loginForm)
        .then(() => {
          router.push({ path: redirect.value || '/' }).catch(() => {})
        })
        .catch(() => {
          loading.value = false
          if (captchaEnabled.value) {
            getCode()
          }
        })
    }
  })
}

// 切换注册/登录
const handleType = (type: number) => {
  isRegister.value = type == 0 ? true : false
  stepIndex.value = 0
}

// 获取短信验证码
const getSmsCode = debounce(
  async () => {
    if (isRegister.value) {
      if (!registerForm.phone.trim()) return ElMessage.error('请输入手机号')
      if (!phoneRegex.test(registerForm.phone)) return ElMessage.error('手机号格式不正确')
      const params = {
        phone: registerForm.phone,
      }
      await sendLoginNoByPhone(params)
    } else {
      if (!loginForm.username.trim()) return ElMessage.error('请输入账号')
      const params = {
        userName: loginForm.username,
        mobile: loginForm.mobile,
      }
      await sendLoginNoByName(params)
    }
    sendCode()
  },
  1000,
  { leading: true, trailing: false },
)

// 60秒倒计时
const sendCode = () => {
  if (countdown.value === 0) {
    countdown.value = 60
    timer.value = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--
      } else {
        if (timer.value) clearInterval(timer.value)
      }
    }, 1000)
  }
}

// 注册下一步
const handleStep = debounce(
  async (index: number) => {
    if (index == 1) {
      registerFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          await checkPhone(registerForm)
          stepIndex.value = index
        }
      })
    } else {
      stepIndex.value = index
    }
  },
  1000,
  { leading: true, trailing: false },
)

// 注册
const handleRegister = debounce(
  async () => {
    registerFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        const params = {
          dept: { deptName: registerForm.deptName },
          phonenumber: registerForm.phone,
          userName: registerForm.userName,
          password: registerForm.password,
        }
        const res = await registerPcUser(params)
        ElMessage.success(res.msg)
        isRegister.value = false
      }
    })
  },
  1000,
  { leading: true, trailing: false },
)

// 处理下一步
const handleNext = () => {
  if (!loginForm.username.trim()) {
    return ElMessage.error('请输入账号')
  } else {
    loginNext.value = !loginNext.value
    if (loginNext.value) {
      loading.value = true
      loginNextLogin.value = true
      getMobile({ userName: loginForm.username })
        .then((res) => {
          loginNextLogin.value = false
          loading.value = false
          loginForm.mobile = res.data
        })
        .catch(() => {
          loading.value = false
          loginNextLogin.value = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login_bg.jpg');
  background-size: cover;
}
.login_box {
  padding: 73px 0 25px;
  background: #fff;
  height: auto;
  box-sizing: border-box;
  width: 488px;
  border-radius: 28px;
  margin-right: 175px;
  .title {
    text-align: center;
    color: #383838;
    font-size: 48px;
    margin: 17px auto 26px;
    // font-weight: bold;
    line-height: 66px;
  }
  .logo {
    text-align: center;
    img {
      width: 100px;
      height: 100px;
    }
  }
}
:deep(.login-form) {
  padding: 0 65px;
  .el-input {
    height: 57px;
    input {
      height: 57px;
      padding-left: 60px;
      font-size: 18px;
    }
    .el-input__prefix {
      display: flex;
      align-items: center;
      left: 20px;
    }
    .el-input__suffix {
      right: 17px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .code_box {
    display: flex;
    width: 100%;
    .el-input {
      flex: 1;
    }
  }
  .el-button {
    height: 57px;
    font-size: 18px;
    border-radius: 13px;
    &.login_btn {
      background: #2187ed;
    }
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  height: 57px;
  margin-left: 20px;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 57px;
}
.form_btm {
  .register {
    font-size: 14px;
    color: #2187ed;
    margin-top: 18px;
    line-height: 21px;
    cursor: pointer;
  }
}
.go_login {
  margin-bottom: 31px;
  font-size: 20px;
  span {
    color: #2a82e4;
    cursor: pointer;
  }
}
.form_btn {
  display: flex;
  margin-top: 56px;
  .step_btn {
    width: 155px;
    height: 57px;
    line-height: 57px;
    border-radius: 13px;
    background: #ffffff;
    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.25);
    text-align: center;
    font-size: 18px;
    cursor: pointer;
  }
  .register_btn {
    flex: 1;
    height: 57px;
    line-height: 57px;
    text-align: center;
    border-radius: 13px;
    background: #2a82e4;
    font-size: 18px;
    color: #fff;
    margin-left: 17px;
    cursor: pointer;
  }
}
</style>
